<!-- <template>
  <Table filter v-bind="tableOpts" v-on="tableEvent">
    <template #operator>
      <div class="operator-wrap">
        <modifySalelist ref="dialogRef" @change="fetchCurrentTable" />
        <SaleMaterials ref="SaleMaterials" @change="fetchCurrentTable" />
        <modifyInOutInventory
          ref="modifyInOutInventory"
          @change="fetchCurrentTable"
        />
      </div>
    </template>
  </Table>
</template>

<script>
import dayjs from "dayjs";
import modifySalelist from "./components/modifySalelist.vue";
import SaleMaterials from "./dialog/SaleMaterials.vue";
import tableMixins from "@/mixins/tableMixins.vue";
import modifyInOutInventory from "./components/modifyInOutInventory.vue";
export default {
  name: "SaleList",
  mixins: [tableMixins],
  components: { modifySalelist, SaleMaterials, modifyInOutInventory },
  meta: { title: "销售订单", icon: "el-icon-s-management", sort: 20 },
  data() {
    return {
      apiName: "saleSaleList",
      form: {
        date: {
          tag: "el-date-picker",
          label: "时间范围",
          value: [],
          props: {
            rangeSeparator: "至",
            startPlaceholder: "开始时间",
            endPlaceholder: "结束时间",
            type: "daterange",
          },
        },
        saleId: {
          tag: "el-input",
          label: "报货单编号",
          value: "",
          props: {
            clearable: true,
            placeholder: "请输入报货单编号",
          },
        },
        warehouseId: {
          tag: "el-select",
          label: "仓库",
          value: "",
          items: [],
          props: {
            clearable: true,
            filterable: true,
          },
        },
        outStatus: {
          tag: "el-select",
          label: "出库状态",
          value: "",
          items: [
            { label: "未出库", value: 0 },
            { label: "已出库", value: 1 },
          ],
          props: {
            clearable: true,
            filterable: true,
          },
        },
      },
    };
  },
  watch: {
    "$store.state.warehouseList": function () {
      this.setItems();
    },
  },
  activated() {
    setTimeout(() => {
      this.setItems();
    }, 100);
  },
  methods: {
    setItems() {
      this.form.warehouseId.items = this.$store.getters.warehouseListItems;
      this.formKey = this.$quinn.guid();
    },
    formatData(res) {
      this.total = res?.count || res?.total || 0;
      this.dataSource = (res?.rows || res?.data || res || []).map((e) => {
        if (e.updatedAt)
          e.updatedTime = dayjs(e.updatedAt).format("YYYY-MM-DD HH:mm:ss");
        if (e.createdAt) {
          e.createdTime = dayjs(e.createdAt).format("YYYY-MM-DD HH:mm:ss");
        }
        e.warehouseName = e?.warehouse?.warehouseName;
        e.warehouseContacts = e?.warehouse?.warehouseContacts;
        if (e.paymentVouchers)
          e.paymentVouchers = `${e.paymentVouchers}`.split(",");
        return e;
      });
    },
    handleAction(opts, row) {
      const {
        orderName: name,
        saleId,
        warehouseName,
        storeName,
        storeContacts,
        storeAddress,
        createdTime,
        warehouseContacts,
      } = row;
      if (["edit"].includes(opts)) this.showDialog(opts, row);
      else if (opts === "modifyInOutInventory") {
        const ref = this.$refs["modifyInOutInventory"];
        ref &&
          ref.showDialog(opts, {
            ...row,
            targetId: row.saleId,
            type: "sale",
          });
      } else if (opts == "import") {
        try {
          const el = document.getElementById("saleUploader");
          const inputer = el.getElementsByTagName("input")[0];
          this.$refs.dialogRef.modifyType = "import";
          this.$refs.dialogRef.modifyRow = row;
          inputer.click();
        } catch (e) {
          console.log(e);
        }
      } else if (opts == "download") {
        let prds = [];
        let totalPrice = 0;
        this.$api["saleSaleMaterials"]({ saleId }).then((res) => {
          try {
            prds = (res || []).map((e, i) => {
              const total = this.$acc.mul(e.salePrice, e.count);
              totalPrice = this.$acc.add(total, totalPrice);
              return [
                i + 1,
                e.materialName,
                e.norm,
                e.color,
                e.count,
                e.unit,
                e.salePrice,
                total,
              ];
            });
            this.$quinn.downloadSale({
              excelName: `${storeName + saleId}`,
              出仓仓库: warehouseName,
              日期: createdTime,
              门店名称: storeName,
              门店位置: storeAddress,
              门店联系人: storeContacts,
              仓库联系人: warehouseContacts,
              合计: totalPrice,
              list: [...prds, ["合计：", totalPrice]],
            });
          } catch (err) {
            console.log(err);
          }
        });
      } else if (opts === "delete")
        this.showConfirm(`确认删除【${name}】？`, "supplierSupplierDelete", {
          supplierId,
        });
      else {
        const ref = this.$refs[opts];
        ref && ref.showDialog(opts, row);
      }
    },
  },
};
</script>

<style lang="less" scoped></style> -->
<script>
import dayjs from "dayjs";
import quinn from "@/utils/quinn";
import saleOrderTable from '@/RayComponents/importSaleOrder.vue'
import changeBox from '@/RayComponents/materialChange.vue'
import Decimal from "decimal.js";
import * as XLSX from 'xlsx-js-style';
// import XLSXStyle from 'xlsx-style'
import { LOGIN_PATH } from '../../assets/js/define';

export default {
  name: "SaleList",
  meta: { title: "销售订单", icon: "el-icon-s-management", sort: 4, authority: 106 },
  components: {
    saleOrderTable,
    changeBox
  },
  data() {
    return {
      list1: [],
      tabClickIndex: "",
      targetId: '',
      listChange: ['admin','王伯维','沈旭滨','王健','袁文典'],
      rejectAccountList: ['admin','王伯维','沈旭滨','王健','袁文典'],
      changeBoxStatus: false,
      importStatus: false,
      pageNumber: 1,
      storeName: '',
      selectionButton: false,
      totalCount: 0,
      pageSize: 20,
      list: [],
      editInfo: {
        storeAddress: '',
        storeContacts: '',
        remark: '',
        saleId: '',
        saleTime: ''
      },
      editRules: {
        storeContacts: [
          { required: true, message: '请输入联系人电话', trigger: 'blur' },
          { min: 2, message: '请输入备注', trigger: 'blur' }
        ],
        storeAddress: [
          { required: true, message: '请输入配送地址', trigger: 'blur' },
          { min: 2, message: '请输入备注', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入备注', trigger: 'blur' },
          { min: 2, message: '请输入备注', trigger: 'blur' }
        ],
      },
      editSaleOrderStatus: false,
      imgHost: this.$imgHost,
      saleId: '',
      maxHeight: 0,
      loading: false,
      currentPage: 1,
      warehouseList: [],
      selectDownLoad: [],
      warehouseId: '',
      creator: '',//发起人
      materialsInfo: {},
      //时间筛选
      timeFilter: 'createdAt',
      materialData: [],
      dialogTitle: '',
      fileType: '',
      saleName: '',
      userName: '',
      statusList: [
        { label: '未出库', value: 0 },
        { label: '已出库', value: 1 },
      ],
      outStatus: ''
    }
  },
  directives: {
    focus: {
      inserted: function (el) {
        el.querySelector('input').focus()
      }
    }
  },
  created() {
    const { userName = [] } =
    quinn.getStorage("userDatav3") || store.state.userData || {};
    this.userName = userName;
    this.saleList();
    this.getWarehouse();
  },
  mounted() {
    this.$nextTick(() => {
      this.maxHeight = window.innerHeight - 240;
    })
    window.onresize = () => {
      this.$nextTick(() => {
        this.maxHeight = window.innerHeight - 240;
      })
    }
  },
  methods: {
    cellClick(row, column) {
      if (column.label === '门店名称') {
        row.isNameSelect = true
      } else if (column.label === '订单类型') {
        row.isTypeSelect = true
      }
    },
    //修改列表订单类型
    changeType(row, curIndex, column) {
      const data = {
        storeName: row.storeName,
        saleId: row.saleId,
        saleType: row.saleType
      }
      this.$api.saleUpdateSaleStoreName(data)
      row.isTypeSelect = false
    },
    //修改列表门店名称
    blurEvent(row, curIndex, column) {
      const data = {
        storeName: row.storeName,
        saleId: row.saleId,
        saleType: row.saleType
      }
      this.$api.saleUpdateSaleStoreName(data)
      row.isNameSelect = false
    },
    focusEvent() {

    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.saleList();
    },
    handleCurrentChange(val) {
      this.pageNumber = val;
      this.saleList();
    },
    getWarehouse() {
      this.$api.warehouseWarehousePullDownList().then(res => {
        this.warehouseList = res;
      })
    },
    close(info) {
      this.importStatus = info;
      setTimeout(() => {
        this.saleList();
      }, 1000)
    },
    createXlsx() {
      this.dialogTitle = '导入报货单'
      this.fileType = 'FILE'
      this.importStatus = true;
    },
    async openImportStatus(info, type) {
      // console.log(info)
      // if (type == 'receive') {
      //   this.dialogTitle = '导入付款凭证'
      // }
      if (type == 'detail') {
        // this.materialsInfo = info
        this.saleGetMaterial(info.saleId, info)
        this.dialogTitle = '查看明细'
      } else if (type == 'outCount') {
        if (info.outStatus == 1) {
          this.$message.error('当前订单已出库，请勿重复点击!');
          return;
        }
        //  this.materialsInfo = info;
        this.saleGetMaterial(info.saleId, info)
        this.dialogTitle = '出库'
      }

      this.fileType = 'IMAGE';


    },
    saleGetMaterial(id, info) {
      let params = {
        saleId: id
      }
      this.$api.saleSaleMaterials(params).then(res => {
        this.materialsInfo = info
        this.materialsInfo.materials = res;
        if (this.materialsInfo.materials.length > 0) {
          this.importStatus = true;
        }

      })
    },
    async saveFile(info) {
      const wb = XLSX.utils.book_new();
      let params = {
        saleId: info.saleId
      }
      this.$api.saleSaleMaterials(params).then(res => {
        let totalSalePriceAmount = new Decimal(0);
        let data = []
        console.log(this.userName)
        if (this.userName === 'CZCYWY' || this.userName === "admin") {
          data = [
            [info.storeName + '   ' + info.createdAt],
            [`仓库:${info.warehouse.warehouseName}`, '', `实付:${info.receivedAmount}`, ''],
            [`补贴:${info.subAmount}`, '', `总价:${info.paymentAmount}`, ''],
            [`联系人:${info.storeContacts}${info.mobile}`, '', `地址:${info.storeAddress}`, ''],
            ['商品编码', '商品名称', '色号', '数量', "单价", "小计"]]
          res.map(el => {
            if (el.count !== 0) {
              data.push([el.materialId, el.materialName, el.color, el.count, el.salePrice, Decimal(el.count).mul(Decimal(el.salePrice)).toNumber(),]);
              totalSalePriceAmount = Decimal(totalSalePriceAmount).plus(Decimal(el.count).mul(Decimal(el.salePrice)).toNumber()).toNumber();
            }
          })
          data[data.length + 1] = [`合计金额:${totalSalePriceAmount}`]
        } else {
          data = [
            [info.storeName + '   ' + info.createdAt],
            [`仓库:${info.warehouse.warehouseName}`, '', ],
            [`联系人:${info.storeContacts}${info.mobile}`, '', `地址:${info.storeAddress}`, ''],
            ['商品编码', '商品名称', '色号', '数量']]
          res.map(el => {
            if (el.count !== 0) {
              data.push([el.materialId, el.materialName, el.color, el.count]);
              totalSalePriceAmount = Decimal(totalSalePriceAmount).plus(Decimal(el.count).mul(Decimal(el.salePrice)).toNumber()).toNumber();
            }
          })
        }
        const ws = XLSX.utils.aoa_to_sheet(data);
        ws['!cols'] = [
          { wpx: 200 }, // 第一列宽度为250单位
          { wpx: 100 }, // 第二列宽度为300单位
          { wpx: 100 },  // 第三列宽度为350单位
          { wpx: 100 },
          { wpx: 100 },
          { wpx: 100 }
        ];
        ws["A1"].s = {
          alignment: { horizontal: 'center' },
          font: { blod: true, color: { rgb: '000000' } },
          fill: { fgColor: { rgb: 'ff6a00' } }
        }
        ws["A1"].hpt = 140;
        // 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

        // 导出工作簿为 Blob 对象
        ws['!merges'] = [{ s: { r: 0, c: 0 }, e: { r: 0, c: 3 } }, { s: { r: 1, c: 0 }, e: { r: 1, c: 1 } }, {
          s: {
            r: 1,
            c: 2
          }, e: { r: 1, c: 3 }
        }, { s: { r: 2, c: 0 }, e: { r: 2, c: 1 } }, { s: { r: 2, c: 2 }, e: { r: 2, c: 3 } }, {
          s: { r: 3, c: 0 },
          e: { r: 3, c: 1 }
        }, { s: { r: 3, c: 2 }, e: { r: 3, c: 3 } }]
        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

        // 创建一个 Blob 对象
        const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });

        // 使用 Blob 对象创建一个链接
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `${info.storeName}${new Date().getTime()}.xlsx`;

        // 触发下载
        link.click();

        // 清理
        URL.revokeObjectURL(link.href);

        function s2ab(s) {
          const buf = new ArrayBuffer(s.length);
          const view = new Uint8Array(buf);
          for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
          return buf;
        }
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.editInfo.saleTime) {
            this.editInfo.saleTime = dayjs(this.editInfo.saleTime).format('YYYY-MM-DD');
          } else {
            this.$message.error('请选择时间!');
            return;
          }
          this.$api.saleSaleInfoUpdate(this.editInfo).then(res => {
            this.editSaleOrderStatus = false;
            this.saleList();
          })
        } else {
          return false;
        }
      });
    },
    downloadTodayData() {
      if (this.warehouseId == '') {
        this.$message.error('请发货仓库,再导出数据!');
        return
      }
      let params = {
        pageNumber: 1,
        pageSize: 100000,
        warehouseId: this.warehouseId,//云南5 贵州11
        type: 'web',
        startTime: dayjs().format('YYYY-MM-DD'),
        endTime: dayjs().add(1, 'day').format('YYYY-MM-DD')
      }
      this.$api.saleSaleList(params).then(res => {

        let demoDataArr = res.rows;
        const wb = XLSX.utils.book_new();
        let data = [['店名', '创建时间', '总价', '回款金额', '折扣金额', '仓库']]

        demoDataArr.map(el => {
          data.push([el.storeName, el.createdAt, el.paymentAmount, el.receivedAmount, el.subAmount, el.warehouse.warehouseName])
        })
        console.log(data);
        const ws = XLSX.utils.aoa_to_sheet(data);
        ws['!cols'] = [
          { wpx: 200 }, // 第一列宽度为250单位
          { wpx: 200 }, // 第二列宽度为300单位
          { wpx: 100 },  // 第三列宽度为350单位
          { wpx: 100 },
          { wpx: 100 },
          { wpx: 100 }
        ];
        // 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

        // 导出工作簿为 Blob 对象
        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

        // 创建一个 Blob 对象
        const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });

        // 使用 Blob 对象创建一个链接
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        let warehouseName = ''
        if (this.warehouseId == 1) warehouseName = '宁乡仓';
        if (this.warehouseId == 2) warehouseName = '广东仓';
        if (this.warehouseId == 4) warehouseName = '广西仓';
        if (this.warehouseId == 5) warehouseName = '云南仓';
        if (this.warehouseId == 7) warehouseName = '河南仓';
        if (this.warehouseId == 10) warehouseName = '重庆仓';
        if (this.warehouseId == 11) warehouseName = '贵州仓';

        link.download = `${warehouseName} -${dayjs().format('YYYY-MM-DD')}-${new Date().getTime()}.xlsx`;
        // 触发下载
        link.click();

        // 清理
        URL.revokeObjectURL(link.href);

        function s2ab(s) {
          const buf = new ArrayBuffer(s.length);
          const view = new Uint8Array(buf);
          for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
          return buf;
        }


      })
    },
    downloadAll() {
      let params = {
        pageNumber: 1,
        pageSize: 10000,
        warehouseId: this.warehouseId,//云南5 贵州11
        type: 'web'
      }
      this.$api.saleSaleList(params).then(res => {
        let startTime = '2024-06-15'
        let endTime = '2099-05-31'
        let dataArr = []

        // && el.outStatus == 1 //已出库
        // && el.outStatus == 1
        res.rows.map(el => {
          let time = el.createdAt.split(' ')[0];
          if (el.outStatus == 1) {
            dataArr.push(el);
          }

        })
        let demoDataArr = [];
        dataArr.map(el => {
          this.$api.saleSaleMaterials({ 'saleId': el.saleId }).then(res => {
            res[0].storeName = el.storeName
            res[0].time = el.saleTime
            demoDataArr.push(res);
          })
        })

        setTimeout(() => {
          const wb = XLSX.utils.book_new();
          let data = [['店名', '销售时间', '商品编码', '商品数量', '数量', '成本价', '销售价']]

          demoDataArr.map(el => {
            el.map(k => {
              data.push([el[0].storeName, el[0].time, k.materialId, k.materialName, k.count, k.price, k.salePrice])
            })
          })
          const ws = XLSX.utils.aoa_to_sheet(data);
          ws['!cols'] = [
            { wpx: 200 }, // 第一列宽度为250单位
            { wpx: 200 }, // 第二列宽度为300单位
            { wpx: 100 },  // 第三列宽度为350单位
            { wpx: 100 },
            { wpx: 100 },
            { wpx: 100 }
          ];
          // 将工作表添加到工作簿
          XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

          // 导出工作簿为 Blob 对象
          const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

          // 创建一个 Blob 对象
          const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });

          // 使用 Blob 对象创建一个链接
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          let warehouseName = ''
          if (this.warehouseId == 1) warehouseName = '宁乡仓';
          if (this.warehouseId == 2) warehouseName = '广东仓';
          if (this.warehouseId == 4) warehouseName = '广西仓';
          if (this.warehouseId == 5) warehouseName = '云南仓';
          if (this.warehouseId == 7) warehouseName = '河南仓';
          if (this.warehouseId == 10) warehouseName = '重庆仓';
          if (this.warehouseId == 11) warehouseName = '贵州仓';

          link.download = `${warehouseName}-${new Date().getTime()}.xlsx`;


          // 触发下载
          link.click();

          // 清理
          URL.revokeObjectURL(link.href);

          function s2ab(s) {
            const buf = new ArrayBuffer(s.length);
            const view = new Uint8Array(buf);
            for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
          }


        }, 40000)
      })

    },
    searchSaleList() {
      this.pageNumber = 1;
      this.saleList();
    },
    editSaleOrder(info) {
      this.editSaleOrderStatus = true;
      this.editInfo.saleId = info.saleId;
      this.editInfo.saleTime = info.saleTime;
      this.editInfo.remark = info.remark;
      this.editInfo.storeAddress = info.storeAddress;
      this.editInfo.storeContacts = info.storeContacts;
    },
    changeBoxClose(e) {
      this.changeBoxStatus = e;
    },
    changeProcureInfo(info) {
      this.targetId = info.saleId;
      this.changeBoxStatus = true;
    },
    deleteOrder(id) {
      this.$alert(`删除ID为:${id}报货单`, '提示', {
        confirmButtonText: '确定',
        callback: (res) => {
          if (res === 'confirm') {
            this.$api.saleSaleDelete({ 'saleId': id }).then(res => {
              this.saleList();
            })
          }
        }
      });
    },
    rejectSaleOrder(info) {
      if (info.outStatus == 1) {
        this.$message.error('已出库订单,不可驳回!');
        return;
      }
      this.$alert(`驳回:${info.storeName}报货单`, '提示', {
        confirmButtonText: '确定',
        callback: (res) => {
          if (res === 'confirm') {
            this.$api.saleWechatSaleReject({ saleId: info.saleId }).then(res => {
              this.saleList();
            })
          }
        }
      });

    },
    saleList() {
      this.loading = true;
      let params = {
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        outStatus: this.outStatus,
        saleId: this.saleId,
        warehouseId: this.warehouseId,
        storeName: this.storeName,
        userName: this.creator,
        timeFilter: this.timeFilter,
        type: 'web'
      }
      this.$api.saleSaleList(params).then(res => {
        this.loading = false;
        res.rows.map(el => {
          el.isNameSelect = false
          el.isTypeSelect = false
          // el.createdAt = dayjs(el.createdAt).format("YYYY-MM-DDYYYY-MM-DD HH:mm:ss");
          if (el.paymentVouchers) {
            el.paymentVouchers = el.paymentVouchers.split(',');
            el.paymentVouchersList = [];
            el.paymentVouchers.map(k => {
              el.paymentVouchersList.push(this.$imgHost + k);
            })
          }

          if (el.outVouchers) el.outVouchers = el.outVouchers.split(',');


          // if (regex.test(el.remark)) {
          //   const data = JSON.parse(el.remark);
          //   el.remark = data.remark;
          //   // el.mobile = data.mobile ? data.mobile : '-';
          //   el.discountStatus = true;
          // } else {
          //   // el.mobile = '-'
          //   el.remark = el.remark;
          //   //超过6月1号的则开始计算是否为折扣
          //   if (el.saleTime >= '2024-06-01') {
          //     if (el.wechatSaleId.length >= 3) {
          //       //此处为小程序订单
          //     } else {
          //       if (el.remark.indexOf('折扣') > -1) {
          //         //导入报货单 有折扣
          //         el.discountStatus = true;
          //       } else {
          //         //导入报货单 无折扣
          //         el.discountStatus = false;
          //       }
          //     }
          //   } else {
          //     el.discountStatus = false;
          //   }
          // }

          const regex = /^\s*(\{.*\}|\[.*\])\s*$/;
          if (regex.test(el.remark)) {
            const data = JSON.parse(el.remark);
            el.remark = data.remark;
            if (data.mobile) {
              el.mobile = data.mobile
            }
          } else {
            el.mobile ? '' : el.mobile = '-'
          }

          if (el.subAmount === 0) {
            el.discountStatus = false;
            el.discountAmount = '暂无折扣'
          } else {
            el.discountStatus = true;
            el.discountAmount = el.subAmount
          }
          // if (el.discountStatus) {
          //   el.discountAmount = Decimal(el.paymentAmount).sub(Decimal(el.receivedAmount)).toNumber();
          // } else {
          //   el.discountAmount = '暂无折扣'
          // }

        })
        this.list = res.rows;
        this.totalCount = res.count;
      })
    },
    // async downloadChangeData() {
    //   // let totalSalePriceAmount = new Decimal(0);
    //   const promises = this.selectDownLoad.map(async el => {
    //     const res = await this.$api.saleSaleMaterials({ 'saleId': el.saleId });
    //     res[0].storeName = el.storeName;
    //     res[0].time = el.saleTime;
    //     return res.map(a => ({
    //       ...a,
    //       storeName: el.storeName,
    //     }));
    //   });
    //   const results = await Promise.all(promises);
    //
    //   let data = results.map(i => {
    //     return i.map(a => {
    //       if (this.userName === 'CZCYWY' || this.userName === 'admin' || this.userName == '闵祥杰' || this.userName == '陈哲翰') {
    //         return {
    //           商品名称: a.materialName,
    //           商品编码: a.materialId,
    //           数量: a.count,
    //           色号: a.color,
    //           单价: a.salePrice,
    //           小计: Decimal(a.count).mul(Decimal(a.salePrice)).toNumber(),
    //           storeName: a.storeName,
    //         };
    //
    //       } else {
    //         return {
    //           商品名称: a.materialName,
    //           商品编码: a.materialId,
    //           数量: a.count,
    //           色号: a.color,
    //           storeName: a.storeName,
    //         };
    //       }
    //     });
    //   });
    //   // 将嵌套数组转换为对象
    //   const sheets = data.reduce((acc, curr) => {
    //     const storeName = curr[0].storeName;
    //     let totalSalePrice = new Decimal(0);
    //     const sheetData = curr.map(item => {
    //       const { storeName, 小计, ...rest } = item;
    //       if (小计 !== undefined) {
    //         totalSalePrice = totalSalePrice.plus(小计);
    //       }
    //       return rest;
    //     });
    //     // 添加合计行
    //     sheetData.push({
    //       商品名称: '',
    //       商品编码: '',
    //       数量: '',
    //       色号: '',
    //       单价: '合计',
    //       小计: totalSalePrice.toNumber(),
    //     });
    //     acc[storeName] = sheetData;
    //     return acc;
    //   }, {});
    //   const wb = XLSX.utils.book_new();
    //
    //   // 遍历对象的键
    //   for (const sheetName in sheets) {
    //     if (sheets.hasOwnProperty(sheetName)) {
    //       // 将每个子数组转换为一个新的工作表
    //       const sheet = XLSX.utils.json_to_sheet(sheets[sheetName]);
    //       // 将工作表添加到工作簿中
    //       sheet['!cols'] = [
    //         { wpx: 200 }, // 第一列宽度为200单位
    //         { wpx: 200 }, // 第二列宽度为200单位
    //         { wpx: 100 }, // 第三列宽度为100单位
    //         { wpx: 100 }, // 第四列宽度为100单位
    //         { wpx: 100 }, // 第五列宽度为100单位
    //         { wpx: 100 }  // 第六列宽度为100单位
    //       ];
    //       XLSX.utils.book_append_sheet(wb, sheet, sheetName);
    //     }
    //   }
    //
    //   const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
    //
    //   // 创建一个 Blob 对象
    //   const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
    //
    //   // 使用 Blob 对象创建一个链接
    //   const link = document.createElement('a');
    //   link.href = URL.createObjectURL(blob);
    //   link.download = `${new Date().getTime()}.xlsx`;
    //
    //   // 触发下载
    //   link.click();
    //   // 清理
    //   URL.revokeObjectURL(link.href);
    //
    //   function s2ab(s) {
    //     const buf = new ArrayBuffer(s.length);
    //     const view = new Uint8Array(buf);
    //     for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    //     return buf;
    //   }
    //
    //   //       // 将工作表添加到工作簿
    //
    // },
    async downloadChangeData() {
      const promises = this.selectDownLoad.map(async el => {
        const res = await this.$api.saleSaleMaterials({ 'saleId': el.saleId });
        res[0].storeName = el.storeName;
        res[0].time = el.saleTime;

        return res.map(a => ({
          ...a,
          storeName: el.storeName,
          saleTime: el.saleTime.split(' ')[0]
        }));
      });
      const results = await Promise.all(promises);

      let combinedData = [];

      results.forEach(result => {
        combinedData = combinedData.concat(result);
      });

      let data = combinedData.map(a => {
        // console.log(a.count,a.salePrice,a.materialName)
        if ( this.userName === 'admin' ||this.userName=='王伯维'||this.userName=='沈旭滨'||this.userName=='王健'||this.userName=='袁文典') {
          return {
            商品名称: a.materialName,
            商品编码: a.materialId,
            数量: a.count,
            色号: a.color,
            单价: a.salePrice,
            小计: new Decimal(a.count).mul(new Decimal(a.salePrice)).toNumber(),
            下单时间: a.saleTime,
            storeName: a.storeName,
          };
        } else {
          return {
            商品名称: a.materialName,
            商品编码: a.materialId,
            数量: a.count,
            色号: a.color,
            下单时间: a.saleTime,
            storeName: a.storeName,
          };
        }
      });
      // Create a single sheet for all data
      const sheetName = '列表选中数据'; // Name for the combined sheet
      const wb = XLSX.utils.book_new();
      const sheet = XLSX.utils.json_to_sheet(data);
      sheet['!cols'] = [
        { wpx: 200 }, // 商品名称
        { wpx: 200 }, // 商品编码
        { wpx: 100 }, // 数量
        { wpx: 100 }, // 色号
        { wpx: 100 }, // 单价
        { wpx: 100 }, // 小计
        { wpx: 100 },  //下单时间
        { wpx: 200 }  // 店铺名称
      ];
      XLSX.utils.book_append_sheet(wb, sheet, sheetName);

      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
      const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });

      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `列表选中数据导出${new Date().getTime()}.xlsx`;

      link.click();
      URL.revokeObjectURL(link.href);

      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      }
    },


    handleSelectionChange(val) {
      if (val.length != 0) {
        this.selectionButton = true
        this.selectDownLoad = val
      } else {
        this.selectionButton = false
      }
    }
  }
}
</script>
<template>
  <div class="default">
    <div class="flex">
      <div class="flex">
        <div class="flex">
          <div style="width:120px;text-align: center;">门店名称:</div>
          <el-input clearable placeholder="请输入门店名称" size='small' v-model="storeName"></el-input>
        </div>
        <div class="flex">
          <div style="width:120px;text-align: center;">报货单号:</div>
          <el-input clearable placeholder="请输入报货单号" size='small' v-model="saleId"></el-input>
        </div>
        <div class="flex">
          <div style="width:120px;text-align: center;">发起人:</div>
          <el-input clearable placeholder="请输入报货单号" size='small' v-model="creator"></el-input>
        </div>
        <div class="flex">
          <div style="width:120px;text-align: center;">仓库:</div>
          <el-select v-model="warehouseId" clearable size='small' style="width:100%" placeholder="请选择">
            <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName"
                       :value="item.warehouseId">
            </el-option>
          </el-select>
        </div>
        <div class="flex" style="margin-right: 20px;">
          <div style="width:120px;text-align: center;">状态:</div>
          <el-select clearable v-model="outStatus" size='small' style="width:100%" placeholder="请选择">
            <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
        <div class="flex" style="margin-right: 20px;">
          <div style="width:120px;text-align: center;">时间筛选:</div>
          <el-select clearable v-model="timeFilter" size='small' style="width:100%" placeholder="请选择">
            <el-option label="下单时间" value="saleTime" />
            <el-option label="提交仓库时间" value="createdAt" />
            <el-option label="出库时间" value="outWareTime" />
          </el-select>
        </div>
        <el-button type="primary" @click="searchSaleList" size='small'>查询</el-button>

      </div>
      <el-button type="primary" @click="createXlsx('FILE')" size='small'
                 v-if="!['GD'].includes(userName)">导入报货单
      </el-button>
    </div>
    <div style="margin-top: 20px;">
      <!--  <el-button type="primary" @click="downloadAll" size='small'>全量导出</el-button>-->
      <el-button type="primary" @click="downloadTodayData" size='small'>导出今日</el-button>
      <el-button type="primary" @click="downloadChangeData" size='small' v-if="selectionButton">按选中数据导出</el-button>
    </div>
    <el-table :data="list" v-loading='loading' element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
              :height="maxHeight" tripe border tooltip-effect="dark" style="width: 100%;margin-top:20px;"
              @selection-change="handleSelectionChange"
              :headerCellStyle="{
            'background': '#ff6a00',
            'textAlign': 'center',
            'color': 'white',
            'fontSize': '12px'
          }" :cellStyle="{
            'textAlign': 'center',
            'fontSize': '12px'
          }">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column fixed="left" prop="creatorName" label="创建人" min-width="60"></el-table-column>
      <el-table-column fixed="left" prop="saleId" label="报货单号" min-width="130"></el-table-column>
      <el-table-column fixed="left" prop="storeName" label="门店名称" min-width="180">
        <template slot-scope="scope">
          <el-input v-if="scope.row.isNameSelect&&listChange.includes(userName)" v-model="scope.row.storeName"
                    @focus="focusEvent(scope.row,scope.$index,scope.column)"
                    @blur="blurEvent(scope.row,scope.$index,scope.column)" v-focus></el-input>
          <p @click="cellClick(scope.row, scope.column)" v-else>{{ scope.row.storeName }}</p>
        </template>
      </el-table-column>
      <el-table-column fixed="left" prop="saleTime" label="下单时间" min-width="140"></el-table-column>
      <el-table-column fixed="left" prop="createdAt" label="提交仓库" min-width="140"></el-table-column>
      <el-table-column fixed="left" prop="outTime" label="出库时间" min-width="140"></el-table-column>
      <el-table-column prop="warehouse.warehouseName" label="出货仓库" min-width="100"></el-table-column>
      <el-table-column prop="paymentAmount" label="应收金额" min-width="100"></el-table-column>
      <el-table-column prop="receivedAmount" label="回款金额" min-width="100"></el-table-column>
      <el-table-column prop="discountAmount" label="折扣金额" min-width="100"></el-table-column>
      <el-table-column min-width="80" label="折扣">
        <template slot-scope="scope">
          <el-tag type='success' v-if="scope.row.discountStatus">打折</el-tag>
          <el-tag type='primary' v-else>正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否出库" min-width="80">
        <template slot-scope="scope">
          <el-tag type='danger' v-if="scope.row.outStatus == 0">
            未出库
          </el-tag>
          <el-tag type='success' v-if="scope.row.outStatus == 1">
            已出库
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单类型" min-width="100">
        <template slot-scope="scope">
          <div v-if="scope.row.isTypeSelect&&listChange.includes(userName)">
            <el-select v-model="scope.row.saleType"
                       size="small"
                       @change="changeType(scope.row,scope.$index,scope.column)">
              <el-option label="报货" :value="1"></el-option>
              <el-option label="补货" :value="2"></el-option>
            </el-select>
          </div>
          <div v-else @click="cellClick(scope.row, scope.column)">
            <el-tag type='success' v-if="scope.row.saleType == 1">报货</el-tag>
            <el-tag type='primary' v-else>补货</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="回款凭证" min-width="180px" v-if="!['GD', , 'GX'].includes(userName)">
        <template slot-scope="scope">
          <el-image v-for='(v, i) in scope.row.paymentVouchersList' :key="i" style="width: 50px; height: 50px"
                    ref="preview" :src="v" :preview-src-list="scope.row.paymentVouchersList"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.remark != ''">{{ scope.row.remark }}</div>
          <div v-else>
            <el-link type="danger">暂无备注</el-link>
          </div>
        </template>
      </el-table-column>


      <el-table-column prop="storeAddress" label="配送地址" min-width="200"></el-table-column>

      <el-table-column prop="storeContacts" label="门店联系人" min-width="100"></el-table-column>
      <el-table-column prop="mobile" label="联系电话" min-width="150"></el-table-column>


      <el-table-column fixed="right" label="操作" min-width="200">
        <template slot-scope="scope">
          <div style="display: grid;grid-template-columns: repeat(2,1fr);grid-gap: 10px;">
            <el-link type="success" v-if="userName === 'admin' ||userName=='王伯维'||userName=='沈旭滨'||userName=='王健'||userName=='袁文典'"
                     @click="editSaleOrder(scope.row, 'receive')">编辑
            </el-link>
            <el-link type="danger" v-if="rejectAccountList.includes(userName) && scope.row.outStatus == 0"
                     @click="rejectSaleOrder(scope.row)">驳回
            </el-link>
            <el-link type="primary"
                     v-if="!['qijiayicaiwu', 'jikedengju', 'daisuodengju'].includes(userName)&&scope.row.outStatus==0"
                     @click="openImportStatus(scope.row, 'outCount')">出库
            </el-link>
            <el-link type="warning" @click="openImportStatus(scope.row, 'detail')">查看明细</el-link>
            <el-link type="danger" v-if="userName === 'admin' ||userName=='王伯维'||userName=='沈旭滨'||userName=='王健'||userName=='袁文典'"
                     @click="deleteOrder(scope.row.saleId)">删除
            </el-link>
            <el-link color="#333" v-if="!['jikedengju', 'daisuodengju'].includes(userName)"
                     @click="changeProcureInfo(scope.row)">变更明细
            </el-link>
            <el-link type="info" @click="saveFile(scope.row)">导出</el-link>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="padding: 20px 0;" align="right" @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 30, 40, 50]"
                   layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
    </el-pagination>
    <el-dialog :visible.sync="editSaleOrderStatus" title="编辑销售订单" width='400px'>
      <el-form :model="editInfo" :rules="editRules" ref="editInfo" label-width="100px">
        <el-form-item label="备注" required prop="remark">
          <el-input clearable type='textarea' v-model="editInfo.remark" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item label="配送地址" required prop="storeAddress">
          <el-input clearable v-model="editInfo.storeAddress" placeholder="请输入配送地址"></el-input>
        </el-form-item>
        <el-form-item label="门店联系人" required prop="storeContacts">
          <el-input clearable v-model="editInfo.storeContacts" placeholder="请输入门店联系人"></el-input>
        </el-form-item>
        <el-form-item label="销售时间">
          <el-date-picker style="width: 100%;" v-model="editInfo.saleTime" type="date">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <el-button style="width: 100%;margin-top: 20px;" type="primary" @click="submitForm('editInfo')">立即创建</el-button>
    </el-dialog>
    <el-dialog :visible.sync="importStatus" :showClose="false" :closeOnPressEscape="false" :close-on-click-modal="false"
               :type="dialogTitle" :title="dialogTitle" width="60%" style="padding-top: 0;">
      <saleOrderTable @close='close' style="width: 100%;" :fileType="fileType" :materials="materialsInfo"
                      :statusType="dialogTitle" />
    </el-dialog>
    <changeBox @close="changeBoxClose" apiName="changeSelectChangeDetailList" v-if="changeBoxStatus"
               :targetId="targetId">
    </changeBox>
  </div>
</template>
<style lang="less" scoped>
.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.default /deep/ .el-button {
  border-color: #ff6a00;
  background-color: #ff6a00;
}

.default /deep/ .el-button:hover {
  color: white;
  border-color: #f59a59;
  background-color: #f59a59;
}

/deep/ .el-button:hover {
  color: black;
  border-color: #DCDFE6;
  background-color: white;
}

span /deep/ .el-button:nth-child(2) {
  border-color: #ff6a00;
  background-color: #ff6a00;
}

span /deep/ .el-button:nth-child(2):hover {
  color: white;
  border-color: #f59a59;
  background-color: #f59a59;
}

// .main /deep/ .el-select:hover{
//   border-color:#ff6a00 !important;
// }
//  /deep/ .el-input__inner{
//   border-color: #ff6a00 !important;
// }
/deep/ .el-input__inner:hover {
  border-color: #ff6a00 !important;
}

/deep/ .el-input__inner:focus {
  border-color: #ff6a00 !important;
}

/deep/ .selected {
  color: #ff6a00 !important;
}

/deep/ .active {
  color: #ff6a00 !important;
}

/deep/ .hover {
  color: #ff6a00 !important;
}

/deep/ .selected {
  color: #ff6a00 !important;
}

/deep/ .el-loading-text {
  color: #ff6a00 !important;
}

/deep/ .el-icon-loading {
  color: #ff6a00 !important;
}

/deep/ .el-checkbox__input.is-checked .el-checkbox__inner {
  background: #ff6a00;
  color: #ff6a00;
  border-color: #fff
}

/deep/ .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background: #ff6a00;
  color: #ff6a00;
  border-color: #fff
}
</style>
